<?php
/**
* Page to do the original application setup (should be refactored at some point!)
*
* @author       Fabrice Douteaud <clearbudget@douteaud.com>
* @package      framework
* @access       public
*/

/***********************************************************************

  Copyright (C) 2008  Fabrice douteaud(clearbudget@douteaud.com)

    This file is part of ClearBudget.

    ClearBudget is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    ClearBudget is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with ClearBudget.  If not, see <http://www.gnu.org/licenses/>.

************************************************************************/
include('logic/constants.php');
include('logic/db.class.php');
include('logic/debug.class.php');
include('logic/settings.class.php');
include('logic/context.class.php');
include('logic/propertyKey.class.php');
include('logic/report.class.php');

// GLOBAL OBJECTS
// objects instantiation (order is important!!!)
class_settings::getInstance();
class_context::getInstance();
// if a language is already given, it is used
if(isset($_REQUEST['language']) && $_REQUEST['language']!='' && $_REQUEST['language']!='NULL') class_context::$language = $_REQUEST['language'];
$keys = class_propertyKey::getInstance();

// check if the application is already setup
// if yes we redirect all calls to the application
if(class_settings::setupDone()) {
  header("location: index.php");
  exit();
  }

// some flags
$badUsername = false;
$badPassword = false;
$settingsSuccess = false;

// get the user data
$addRowFlag = false;
$username = @$_REQUEST['username'];
$password = @$_REQUEST['password'];
$language = @$_REQUEST['language'];
$currency = @$_REQUEST['currency'];
$secureAccess = @$_REQUEST['secureAccess'];
isset($_REQUEST['numCategory'])?$numCategory=$_REQUEST['numCategory']:$numCategory  = 1;

for($i=1; $i<=$numCategory;$i++) {
  ${'categoryName'.$i} = @$_REQUEST['categoryName'.$i];
  ${'categoryMaxAmount'.$i} = @$_REQUEST['categoryMaxAmount'.$i];
  ${'categoryColor'.$i} = @$_REQUEST['categoryColor'.$i];
  }
  
// process the request
if($_SERVER["REQUEST_METHOD"]=='POST') {  
  // check if we need to add one table row for categories
  if(isset($_REQUEST['addRow'])) {
    $numCategory = $_REQUEST['numCategory'] + 1;
    $addRowFlag = true;
    }

    // check if the user wants to save
  if(isset($_REQUEST['submit'])) {
    // if we have the request to secure the access to the site, we must have a valid username and password
    if(isset($_REQUEST['secureAccess']) && $_REQUEST['secureAccess'] == '1') {
      // if username and password are valid
      if($username == null || $username == '' || strlen($username)<6) $badUsername = true;
      if($password == null || $password == '' || strlen($password)<6) $badPassword = true;
      if($badUsername || $badPassword) {
        $_REQUEST['secureAccess'] = null;
        }
      }
    
    // save data if mandatory information are present
    if(!$badUsername && !$badPassword && $language!='NULL' && $currency!='NULL' && $language!='' && $currency!='') {
      // update the user settings
      class_settings::$language = $language;
      class_settings::$username = $username;
      class_settings::$password = $password;
      class_settings::$secureAccess = $secureAccess;
      class_settings::$setupDone = true;
      class_settings::$currency = $currency;
      class_settings::updateUserSettings(true);
      $settingsSuccess = true;
      // if there are some category, save then
      $db = class_db::getInstance();
      for($i=1; $i<=$numCategory;$i++) {
        if(${'categoryName'.$i} != null && ${'categoryName'.$i} != '') {
          $db->addFields('name', ${'categoryName'.$i});
          $db->addFields('color', ${'categoryColor'.$i});
          $db->addFields('maxAmountPerMonth', ${'categoryMaxAmount'.$i});
          $db->insert('t_categories');
          }
        }
      // redirect to the main tool
      header("location: index.php?from=setup");
      exit();
      }
    }
  }

function makeCategoryTableRow($rowNum=0, $categoryName=null, $categoryMaxAmount=null, $categoryColor=null) {
  echo '<tr>';
  echo '<td><input type="text" value="'.$categoryName.'" name="categoryName'.$rowNum.'"></td>';
  echo '<td><select name="categoryColor'.$rowNum.'">';
  foreach((array)unserialize(COLORS) as $color) {
    $comp = explode(',', $color);
    echo '<option value="'.$comp[0].'" style="background-color: '.$comp[1].';"';
    if($categoryColor == $comp[0]) echo ' selected';
    echo '>'.$comp[2].'</option>';
    }
  echo '</select></td>';
  echo '<td><input type="text" value="'.$categoryMaxAmount.'" name="categoryMaxAmount'.$rowNum.'"></td>';
  echo '</tr>';
  }

// cache control: no cache
header("Cache-Control: no-cache");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $keys->getLang();?>" lang="<?php echo $keys->getLang();?>">
<head>
  <title><?php @include("ver.txt"); ?></title>
	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<style type="text/css" media="screen"> /*<![CDATA[*/ <!--
    @import url(style/budget.css);
    @import url(style/colors.css);
    @import url(style/tables.css);
    @import url('js/colorPicker/js/jquery.colorPickerAgain.css');
    --> /*]]>*/
    </style>
    <style type="text/css" media="print"> /*<![CDATA[*/ <!--
    @import "template/print.css";
    --> /*]]>*/
    </style>
</head>
<body>	
<div id="wrapper1">
  <div id="wrapper2">
    <div class="header" id="header">
      <h1><?php echo $keys->pageTitle_ReportMain;?></h1>
      <ul>
        <li><img src="style/tr.gif"></li><li><img src="style/fr.gif"></li><li><img src="style/en.jpg"></li>
      </ul>
    </div>
    <div class="columns">
      <div class="leftcolumn sidebar" id="sidebar-left">
        <div class="leftpadding">
          <?php
          echo $keys->text_setupSummary;
          ?>
        </div>
      </div>
      <div class="centercolumn">
        <div class="centerpadding">
          <div class="main-content" id="main">
          
<?php
if($_SERVER["REQUEST_METHOD"]=='POST' && !$addRowFlag) {  
  echo '<blockquote>Error<br/>';
  echo $keys->error_MissingMandatoryUserSettings;
  echo '</blockquote>';
  echo '<br/>';
  if($badUsername || $badPassword) {
    echo '<blockquote>Error<br/>';
    echo $keys->error_InvalidUsernameOrPassword;
    echo '</blockquote>';
    echo '<br/>';
    }
  }
?>
        <form action="setup.php" method="post">
          <input type="hidden" name="numCategory" value="<?php echo $numCategory; ?>">
          <div class="title"><?php echo $keys->pageTitle_accountSettings; ?></div><br/>
          <input type="hidden" name="action" value="settings">
          
          <table class="tableReport" onMouseOver="javascript:trackTableHighlight(event, '#E6EAE9');" onMouseOut="javascript:highlightTableRow(0);">
          <caption><?php echo $keys->pageTitle_accountSettingsSetup; ?></caption>
          <tr>
            <th><?php echo $keys->text_settingName; ?></th>
            <th><?php echo $keys->text_settingInput; ?></th>
          </tr>
          <tr><td><?php echo $keys->text_login; ?></td>
            <td><input type="text" value="<?php echo $username; ?>" name="username" id="login"></td></tr>
          <tr><td><?php echo $keys->text_password; ?></td>
            <td><input type="password" value="<?php echo $password; ?>" name="password" id="password"></td></tr>
          <tr><td><?php echo $keys->text_secureAccess; ?></td>
            <td><select name="secureAccess" id="secureAccess">
            <option value='0' <?php if($secureAccess === '0') echo 'selected';?>><?php echo $keys->text_no; ?></option>
            <option value='1' <?php if($secureAccess == 1) echo 'selected';?>><?php echo $keys->text_yes; ?></option>
            </select></td></tr>
          <tr><td><span style="color:purple;"><?php echo $keys->text_language; ?>*</span></td>
            <td><select name="language" id="language">
            <option value='NULL'><?php echo $keys->link_pickInTheList; ?></option>
            <option value='fr' <?php if($language == 'fr') echo 'selected';?>><?php echo $keys->link_SetLanguageFR; ?></option>
            <option value='en' <?php if($language == 'en') echo 'selected';?>><?php echo $keys->link_SetLanguageEN; ?></option>
            <option value='tr' <?php if($language == 'tr') echo 'selected';?>><?php echo $keys->link_SetLanguageTR; ?></option>
            </select></td></tr>
          <tr><td><span style="color:purple;"><?php echo $keys->text_currency; ?>*</span></td>
            <td><select name="currency" id="currency">
            <option value='NULL'><?php echo $keys->link_pickInTheList; ?></option>
            <option value='euro' <?php if($currency == 'euro') echo 'selected';?>><?php echo $keys->text_euro; ?></option>
            <option value='dollar' <?php if($currency == 'dollar') echo 'selected';?>><?php echo $keys->text_dollar; ?></option>
            </select></td></tr>
          </table>

<br/>

          <div class="title"><?php echo $keys->link_editCategory; ?></div><br/>
          <table class="tableReport" onMouseOver="javascript:trackTableHighlight(event, '#E6EAE9');" onMouseOut="javascript:highlightTableRow(0);">
          <caption><?php echo $keys->text_categorySettingsSetup; ?></caption>
          <tr>
            <th><?php echo $keys->text_categoryNameLong; ?></th>
            <th><?php echo $keys->text_categoryColor; ?></th>
            <th><?php echo $keys->text_categoryMaxAmount; ?></th>
          </tr>
<?php
for($i=1; $i <= $numCategory; $i++) {
  @makeCategoryTableRow($i, ${'categoryName'.$i}, ${'categoryMaxAmount'.$i}, ${'categoryColor'.$i});
  }
?>
          <tr><td colspan="3"  style="text-align:right" >
            <input type="submit" class="submit" name="addRow" value="+">
          </td></tr>
          </table>
<div style="text-align:center">
<input type="submit" class="submit" name="submit" value="Go">
</div><br/>
</form>

          </div>
        </div>
      </div>
    </div>
  <div class="clearing"></div>
    <div id="footer" class="footer">
      <!-- please do not remove the following line -->
      <p id="copyrightnote"><?php @include("ver.txt"); ?></p>
    </div>
  </div>
</div>
</body>
</html>